package academic.ui.client.widgets.forms;

import ui.client.GenericContainerTag;
import ui.client.widgets.InputField;

import academic.ui.client.jquery.JQuery;
import academic.ui.client.rules.Rules;

import com.google.gwt.event.dom.client.HasKeyDownHandlers;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.PasswordTextBox;

public class SignInForm extends FormWidget {

	
	

	private InputField email = new InputField("Email");
	private PasswordTextBox password1 = new PasswordTextBox();
	private GenericContainerTag passwordsDiv = new GenericContainerTag("div");
	private KeyDownHandler removeErrors = new KeyDownHandler() {

		@Override
		public void onKeyDown(KeyDownEvent event) {
			JQuery.fadeOutErrors();
		}
		
	};
	
	public SignInForm() {
		super();
		div.setStyleName("signInForm");
		div.add(email);
		email.getField().setStyleName("longInput");
		password1.setStyleName("longInput");
		GenericContainerTag password1Lbl = new GenericContainerTag("span",
		"Password");
		
		div.add(passwordsDiv);
		
		passwordsDiv.add(password1Lbl);
		passwordsDiv.setStyleName("field");
		passwordsDiv.add(password1);
		
		div.add(this.errorMsgs);
		email.getField().addKeyDownHandler(removeErrors);
		password1.addKeyDownHandler(removeErrors);
	}
	
	@Override
	public Boolean checkRules() {
		errorMsgs.clear();
		if("".equals(email.getText()))
		{
			email.addStyleName("missingValue");
			errorMsgs.add(new GenericContainerTag("div","Email is required."));
		}
		if("".equals(password1.getText()))
		{
			password1.addStyleName("missingValue");
			errorMsgs.add(new GenericContainerTag("div","Password is required."));
		}
		if(!"".equals(email.getText()) && !Rules.validEmail(email.getText()))
		{
			email.addStyleName("invalid");
			errorMsgs.add(new GenericContainerTag("div","Email is not valid."));
		}
		return errorMsgs.getWidgetCount()<1; 
	}

	@Override
	public void removeErrors() {
		errorMsgs.clear();
		email.removeStyleName("missingValue");
		password1.removeStyleName("missingValue");
		email.removeStyleName("invalid");
		passwordsDiv.removeStyleName("invalid");
	}

	public HasText getEmail() {
		return email;
	}

	public HasText getPasswd() {
		return password1;
	}
	
	public HasKeyDownHandlers getpasswdKeyDown() {
		return password1;
	}

	public HasKeyDownHandlers getEmailKeyDown() {
		return email.getField();
	}
	
	public void setEmail(String emailAddr) {
		email.setText(emailAddr);
		email.getField().setEnabled(false);
	}

	public void reset() {
		email.setText("");
		email.getField().setEnabled(true);
		password1.setText("");
		password1.setEnabled(true);
	}

}
